/* 带加载状态的请求 */
import Vue from 'vue'
import axios from 'axios'
import router from 'vue-router'
import qs from 'qs'
import merge from 'lodash/merge'
import {
	clearLoginInfo, getAuthToken
} from 'utils'
import config from './config'
import { Toast } from 'vant'
import cache from "./cache";
import util from "./validate";

//需要loading加载中
const httploading = axios.create({
    timeout: 1000 * 30,
    withCredentials: true,
    headers: {
    	'Content-Type': 'application/json; charset=utf-8',
    	'Access-Control-Allow-Origin': '*', //解决跨域问题
    },
	//解决传参为数组时接口报错问题
	paramsSerializer: (params) => qs.stringify(params, { indices: false })
})

function startLoading() {
    // 开始加载
	uni.showLoading({
	    title: '加载中',
		mask:true //是否显示透明蒙层，防止触摸穿透，默认：false
	});
  //   Toast.loading({
  //       message: '加载中...',
  //       forbidClick: true,
		// duration:0,
		// loadingType: 'spinner'
  //   });
}
function endLoading() {
    // 结束加载
	 uni.hideLoading();
    // Toast.clear()
}
/**
 * 请求拦截
 */
httploading.interceptors.request.use(config => {
	startLoading()
	//获取认证token的请求不拦截
	/*if(config.url.indexOf('/caac-oa-schedule') === -1  ){
		let tokenInfo = cache.get("token")
		//上次获取的token距离当前时间超过1300s时重新获取token
		if(util.isNotEmpty(tokenInfo)){
			if(new Date().getTime()/1000 - tokenInfo.tokenTime > 1300){
				getAuthToken()
				tokenInfo = cache.get("token")
			}
		}else{
			getAuthToken()
			tokenInfo = cache.get("token")
		}
		config.headers['auth-token'] = tokenInfo.token// 请求头带上token
	}*/
	return config
}, error => {
	 setTimeout(() => {
	    endLoading()
	 },5000)
	return Promise.reject(error)
})

/**
 * 响应拦截
 */
httploading.interceptors.response.use(response => {
	if (response.data && response.data.code === 401) { // 401, token失效
		clearLoginInfo()
		router.push({
			name: 'login'
		})
	}
	endLoading()
	return response
}, error => {
	setTimeout(() => {
	   endLoading()
	 },5000)
	return Promise.reject(error)
})



/**
 * 请求地址处理
 * @param {*} actionName action方法名称
 */
httploading.adornUrl = (actionName) => {
	// 非生产环境 && 开启代理, 接口前缀统一使用[/proxyApi/]前缀做代理拦截!
	// return (process.env.NODE_ENV !== 'production' && process.env.OPEN_PROXY ? '/proxyApi/' : window.SITE_CONFIG.baseUrl) + actionName
	// console.log(window.SITE_CONFIG.baseUrl)
	return config.baseUrl + actionName
}

/**
 * get请求参数处理
 * @param {*} params 参数对象
 * @param {*} openDefultParams 是否开启默认参数?
 */
httploading.adornParams = (params = {}, openDefultParams = true) => {
	var defaults = {
		't': new Date().getTime()
	}
	return openDefultParams ? merge(defaults, params) : params
}

/**
 * post请求数据处理
 * @param {*} data 数据对象
 * @param {*} openDefultdata 是否开启默认数据?
 * @param {*} contentType 数据格式
 *  json: 'application/json; charset=utf-8'
 *  form: 'application/x-www-form-urlencoded; charset=utf-8'
 */
httploading.adornData = (data = {}, openDefultdata = true, contentType = 'json') => {
	var defaults = {
		't': new Date().getTime()
	}
	data = openDefultdata ? merge(defaults, data) : data
	return contentType === 'json' ? JSON.stringify(data) : qs.stringify(data)
}


export default httploading
